package cn.zmit.kuxi.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.zmit.kuxi.R;
import cn.zmit.kuxi.activity.binner.SliderBanner;
import cn.zmit.kuxi.adapter.MainSliderBanner;
import cn.zmit.kuxi.cache.ACache;
import cn.zmit.kuxi.contants.Constants;
import cn.zmit.kuxi.contants.SPConstants;
import cn.zmit.kuxi.engine.CommonFunctions;
import cn.zmit.kuxi.entity.MainViewPagerInfoDate;
import cn.zmit.kuxi.entity.NewRecordEntity;
import cn.zmit.kuxi.entity.TodayHotEnity;
import cn.zmit.kuxi.holder.MainNewRecordHolder;
import cn.zmit.kuxi.holder.TodayHotHolder;
import cn.zmit.kuxi.interfaces.OnAddToCartAnimationFinishListener;
import cn.zmit.kuxi.interfaces.OnAddToCartClickListener;
import cn.zmit.kuxi.request.RequestTask;
import cn.zmit.kuxi.utils.CommonUtils;
import cn.zmit.kuxi.view.BottomScrollView;
import cn.zmit.kuxi.view.BottomScrollView.OnScrollToBottomListener;
import cn.zmit.kuxi.view.HorizontalListView;
import cn.zmit.kuxi.widget.CompatibleGridViewWithScrollview;
import cn.zmit.kuxi.widget.PtrHeader;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.util.LogUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.umeng.analytics.MobclickAgent;
import com.viewpagerindicator.LinePageIndicator;
import com.xdroid.common.utils.ImageUtils;
import com.xdroid.common.utils.PreferenceHelper;
import com.xdroid.common.utils.ScreenUtils;
import com.xdroid.functions.holder.ListViewDataAdapter;
import com.xdroid.functions.request.JsonData;
import com.xdroid.request.extension.XDroidRequest;
import com.xdroid.request.extension.config.DataType;
import com.xdroid.request.extension.impl.OnRequestListenerAdapter;
import com.xdroid.widget.ptr.PtrDefaultHandler;
import com.xdroid.widget.ptr.PtrFrameLayout;
import com.xdroid.widget.ptr.PtrHandler;

public class MainActivity extends BaseActivity implements
		OnAddToCartAnimationFinishListener,
		OnAddToCartClickListener<TodayHotEnity>, OnClickListener {
	@ViewInject(R.id.listview_new_battlefield)
	private HorizontalListView listView_new;
	private ListViewDataAdapter<NewRecordEntity> newRecordAdapter;
	@ViewInject(R.id.indicator)
	private LinePageIndicator indicator;//
	private String banner_path;// 广告图路径

	@ViewInject(R.id.slider_banner)
	private SliderBanner sliderBanner;

	@ViewInject(R.id.editext_keywords)
	private TextView editext_keywords;// 输入关键字
	@ViewInject(R.id.rl_new)
	private RelativeLayout rl_new;// 最新战报
	@ViewInject(R.id.rl_today)
	private RelativeLayout rl_today;// 今日热门
	@ViewInject(R.id.gridView)
	private CompatibleGridViewWithScrollview gridView;//
	private ListViewDataAdapter<TodayHotEnity> todayHotAdapter;

	List<NewRecordEntity> mNewRecordList = new ArrayList<NewRecordEntity>();

	/**
	 * 轮播图控制器
	 */
	private MainSliderBanner mainSliderBanner;

	// 下拉刷新
	@ViewInject(R.id.ptr_view)
	private PtrFrameLayout ptr_view;
	private PtrHeader ptrHeader;

	private List<MainViewPagerInfoDate> mainViewPagerInfoDate = new ArrayList<MainViewPagerInfoDate>();
	private static final int MSG_CHANGE_PHOTO = 1;
	private String userid = null;

	/**
	 * 首页分页 @author:Joash_Yan
	 * 
	 */
	private int mPage = 1;

	// 显示listView
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		ViewUtils.inject(this);
		ShareSDK.initSDK(this);
		bt_share = (Button) findViewById(R.id.bt_share);
		bt_share.setOnClickListener(this);
		// bt_share.setVisibility(View.GONE);

		Button btn_gotop = (Button) findViewById(R.id.btn_gotop);
		final BottomScrollView sc_scroll = (BottomScrollView) findViewById(R.id.sc_scroll);
		CommonFunctions.getInstance().setOnAddToCartAnimationFinishListener(
				this);
		btn_gotop.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				sc_scroll.fullScroll(ScrollView.FOCUS_UP);
				initPtr();

			}
		});
		mCache = ACache.get(this);

		// 初始化listView
		intiNewRecord();
		initSliderBanner();
		initPtr();// 下拉刷新

		/**
		 * listener scrollToBottom
		 * 
		 * @author Joash_Yan
		 */
		sc_scroll.setOnScrollToBottomLintener(new OnScrollToBottomListener() {

			@Override
			public void onScrollBottomListener(boolean isBottom) {
				if (isBottom == true
						&& gridView.getLastVisiblePosition() == 8 * mPage - 1) {
					mPage++;
					newRecordAdapter.removeAll();
					getData();
				}
			}
		});

	}

	private void intiNewRecord() {
		newRecordAdapter = new ListViewDataAdapter<NewRecordEntity>();
		newRecordAdapter.setViewHolderClass(this, MainNewRecordHolder.class);
		listView_new.setAdapter(newRecordAdapter);
		// listView_new.setOnTouchListener(new OnTouchListener() {
		//
		// @Override
		// public boolean onTouch(View arg0, MotionEvent arg1) {
		//
		// switch (arg1.getAction()) {
		// case MotionEvent.ACTION_MOVE:
		// return true;
		//
		// default:
		// break;
		// }
		// return false;
		// }
		// });

		todayHotAdapter = new ListViewDataAdapter<TodayHotEnity>();
		todayHotAdapter.setViewHolderClass(this, TodayHotHolder.class);
		TodayHotHolder.setOnAddToCartClickListener(this);
		gridView.setAdapter(todayHotAdapter);
	}

	/**
	 * 初始化轮播图
	 */
	private void initSliderBanner() {
		RelativeLayout.LayoutParams lyp = new RelativeLayout.LayoutParams(
				ScreenUtils.getScreenWidth(context),
				(int) (ScreenUtils.getScreenWidth(context) * 1f / 16 * 9.6f));
		sliderBanner.setLayoutParams(lyp);
		mainSliderBanner = new MainSliderBanner(sliderBanner);
	}

	@OnClick({ R.id.rl_new, R.id.rl_today, R.id.editext_keywords })
	private void Onclick(View v) {
		switch (v.getId()) {
		case R.id.rl_new:// 最新战报
			Bundle bundle = new Bundle();
			bundle.putString("flag", "首页");
			bundle.putInt("jump_index", 2);
			openActivity(HomeActivity.class, bundle);
			break;
		case R.id.rl_today:// 今日热门
			Bundle bundle1 = new Bundle();
			bundle1.putString("flag", "首页");
			bundle1.putInt("jump_index", 1);
			openActivity(HomeActivity.class, bundle1);
			break;
		case R.id.editext_keywords:// 输入关键字
			openActivity(SearchActivity.class);

			break;
		default:
			break;
		}
	}

	/**
	 * 初始化下拉刷新
	 */
	private void initPtr() {
		/* 创建自定义刷新头部view */
		ptrHeader = new PtrHeader(this);
		/* 设置刷新头部view */
		ptr_view.setHeaderView(ptrHeader);
		/* 设置回调 */
		ptr_view.addPtrUIHandler(ptrHeader);
		/* 横向拉动时，禁止下拉 */
		ptr_view.disableWhenHorizontalMove(true);
		// 设置监听
		ptr_view.setPtrHandler(new PtrHandler() {

			@Override
			public void onRefreshBegin(PtrFrameLayout frame) {
				frame.postDelayed(new Runnable() {

					@Override
					public void run() {
						mPage = 1;
						newRecordAdapter.removeAll();
						todayHotAdapter.removeAll();
						mainViewPagerInfoDate.clear();
						getData();
					}
				}, 500);
			}

			@Override
			public boolean checkCanDoRefresh(PtrFrameLayout frame,
					View content, View header) {
				return PtrDefaultHandler.checkContentCanBePulledDown(frame,
						content, header);
			}
		});
		/* 延时100hao秒,自动刷新 */
		ptr_view.postDelayed(new Runnable() {

			@Override
			public void run() {
				ptr_view.autoRefresh();
			}
		}, 100);
	}

	Boolean hasLog;

	// 请求
	private void getData() {
		hasLog = PreferenceHelper.readBoolean(context,
				SPConstants.SHARED_PREFERENCE_NAME, SPConstants.HAS_LOGGED,
				false);
		if (hasLog) {
			userid = PreferenceHelper.readString(context,
					SPConstants.SHARED_PREFERENCE_NAME, SPConstants.USERID, "");
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("user_id", userid);
			RequestTask.getInstance().doMain(this, map, mPage + "",
					new OnRequestListener());
		} else {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("user_id", 0);
			RequestTask.getInstance().doMain(this, map, mPage + "",
					new OnRequestListener());
		}
	}

	String goods_name;
	String phone;
	String picture;
	private Button bt_share;

	// 缓存
	private ACache mCache;

	// 获取首页
	private class OnRequestListener extends OnRequestListenerAdapter<Object> {
		@SuppressWarnings("deprecation")
		@Override
		public void onDone(XDroidRequest<?> request, String response,
				DataType dataType) {
			super.onDone(request, response, dataType);

			dismissProgressDialog();

			JsonData jsonData = JsonData.create(response);

			mCache.put("today_hot", response);
			if (response != null) {

				mainSliderBanner.play(jsonData.optJson("banner"), true);
				LogUtils.e("图片解析：" + jsonData.optJson("banner"));

				JsonData newest_record_data = jsonData.optJson("newest_record");
				int nowtime = jsonData.optInt("now_time");
				for (int i = 0; i < 3; i++) {
					JsonData itemData = newest_record_data.optJson(i);
					goods_name = itemData.optString("goods_name");
					phone = itemData.optString("phone");
					String pic = itemData.optString("pic");
					String gp_id = itemData.optString("gp_id");
					String title = itemData.optString("phase");
					int oldtime = itemData.optInt("announceOn");
					NewRecordEntity newRecordEntity = new NewRecordEntity(
							goods_name, phone, gp_id, title, oldtime, nowtime,
							pic);
					newRecordAdapter.append(newRecordEntity);
				}

				JsonData top_today_data = jsonData.optJson("top_today");
				for (int j = 0; j < top_today_data.length(); j++) {
					JsonData itemDate = top_today_data.optJson(j);
					String joinName = itemDate.optString("buy_count");
					String goodsName = itemDate.optString("name");
					String goodsAll = itemDate.optString("price");
					String title = itemDate.optString("phase");
					String pic = itemDate.optString("pic");
					String gp_id = itemDate.optString("gp_id");
					if (hasLog) {
						String status = itemDate.optString("status");
						TodayHotEnity todayHotEnity = new TodayHotEnity(title,
								goodsName, joinName, goodsAll, pic, gp_id,
								status);
						todayHotAdapter.append(todayHotEnity);
					} else {
						TodayHotEnity todayHotEnity = new TodayHotEnity(title,
								goodsName, joinName, goodsAll, pic, gp_id);
						todayHotAdapter.append(todayHotEnity);
					}
				}
				ptr_view.refreshComplete();
			}
		}

		@Override
		public void onRequestFailed(String error) {
			// super.onRequestFailed(error);
			// ptr_view.refreshComplete();
			// dismissProgressDialog();
			if (mPage == 1) {
				JsonData jsonDataCache = JsonData.create(mCache
						.getAsString("today_hot"));

				mainSliderBanner.play(jsonDataCache.optJson("banner"), true);

				JsonData newest_record_data = jsonDataCache
						.optJson("newest_record");
				int nowtime = jsonDataCache.optInt("now_time");
				for (int i = 0; i < 3; i++) {
					JsonData itemData = newest_record_data.optJson(i);
					goods_name = itemData.optString("goods_name");
					phone = itemData.optString("phone");
					String pic = itemData.optString("pic");
					String gp_id = itemData.optString("gp_id");
					String title = itemData.optString("phase");
					int oldtime = itemData.optInt("announceOn");
					NewRecordEntity newRecordEntity = new NewRecordEntity(
							goods_name, phone, gp_id, title, oldtime, nowtime,
							pic);
					newRecordAdapter.append(newRecordEntity);
				}

				JsonData top_today_data = jsonDataCache.optJson("top_today");
				for (int j = 0; j < top_today_data.length(); j++) {
					JsonData itemDate = top_today_data.optJson(j);
					String joinName = itemDate.optString("buy_count");
					String goodsName = itemDate.optString("name");
					String goodsAll = itemDate.optString("price");
					String title = itemDate.optString("phase");
					String pic = itemDate.optString("pic");
					String gp_id = itemDate.optString("gp_id");
					if (hasLog) {
						String status = itemDate.optString("status");
						TodayHotEnity todayHotEnity = new TodayHotEnity(title,
								goodsName, joinName, goodsAll, pic, gp_id,
								status);
						todayHotAdapter.append(todayHotEnity);
					} else {
						TodayHotEnity todayHotEnity = new TodayHotEnity(title,
								goodsName, joinName, goodsAll, pic, gp_id);
						todayHotAdapter.append(todayHotEnity);
					}
				}
				ptr_view.refreshComplete();
			} else {
				Toast.makeText(MainActivity.this, "网络异常！", 0).show();
			}

		}

		@Override
		public void onRequestPrepare() {
			super.onRequestPrepare();
		}
	}

	// 发送事件，通知购物车角标更新
	@Override
	public void OnAddToCartAnimationFinish() {

	}

	// 购物车点击动画
	@Override
	public void onAddToCartClick(int postion, View v, TodayHotEnity entityData,
			Drawable productDrawable, Boolean mHasOption) {
		ImageView buyImg = new ImageView(context);// 创建执行动画的控件
		// buyImg.setImageDrawable(productDrawable);// 设置控件图片，这里使用的是商品的图片
		buyImg.setImageBitmap(ImageUtils.getRoundedCornerBitmap(CommonUtils
				.drawableToBitmap(productDrawable,
						(int) ScreenUtils.dpToPx(context, 160),
						(int) ScreenUtils.dpToPx(context, 120)), 360));

		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
				(int) ScreenUtils.dpToPx(context, 100),
				(int) ScreenUtils.dpToPx(context, 100));

		int[] start_location = new int[2];// 存储起始坐标X,Y数组
		v.getLocationInWindow(start_location);// 获取view在屏幕的位置，即起始坐标

		/* 计算结束坐标 */
		if (postion % 2 == 0) {
			int endX = (ScreenUtils.getScreenWidth(context) / 5) * 4;
			int endY = (int) (ScreenUtils.getScreenHeight(context) - ScreenUtils
					.dpToPx(context, 45));
			CommonFunctions.getInstance().setAddToCartAnimationRight(this,
					buyImg, lp, start_location, endX, endY);
		} else {
			int endX = (int) (ScreenUtils.getScreenWidth(context) - ((ScreenUtils
					.getScreenWidth(context) / 5) * 4));
			int endY = (int) (ScreenUtils.getScreenHeight(context) - ScreenUtils
					.dpToPx(context, 45));
			CommonFunctions.getInstance().setAddToCartAnimation(this, buyImg,
					lp, start_location, endX, endY);
		}
	}

	@Override
	protected void onResume() {
		if (Constants.REFRESH_TAG == 1) {
			initPtr();
			Constants.REFRESH_TAG = 0;
		}
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	public void onClick(View arg0) {
		OnekeyShare oks = new OnekeyShare();
		// 关闭sso授权
		oks.disableSSOWhenAuthorize();
		// title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
		oks.setTitle(getString(R.string.share));
		// titleUrl是标题的网络链接，仅在人人网和QQ空间使用
		oks.setTitleUrl("http://www.aikuxi.com/api/apk/dl");
		// text是分享文本，所有平台都需要这个字段
		oks.setText("一元中大奖，快来酷喜乐购试试你的人品吧！http://www.aikuxi.com/api/apk/dl");
		// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
		// oks.setImagePath("/sdcard/test.jpg");// 确保SDcard下面存在此张图片
		oks.setImageUrl("http://www.aikuxi.com/bundles/website/images/m_logo.png");
		// url仅在微信（包括好友和朋友圈）中使用
		oks.setUrl("http://www.aikuxi.com/api/apk/dl");

		// comment是我对这条分享的评论，仅在人人网和QQ空间使用
		oks.setComment("一元就能中大奖，太棒啦！");
		// site是分享此内容的网站名称，仅在QQ空间使用
		oks.setSite(getString(R.string.app_name));
		// siteUrl是分享此内容的网站地址，仅在QQ空间使用
		oks.setSiteUrl("http://www.aikuxi.com/api/apk/dl");

		// 启动分享GUI
		oks.show(this);
	}

	// check intalled app
	// public Boolean isInstalled(Context context) {
	// PackageManager pm = getPackageManager();
	// List<PackageInfo> infos = pm.getInstalledPackages(0);
	// for (PackageInfo info : infos) {
	// if (info.packageName.equals("cn.zmit.kuxi")) {
	// return true;
	// }
	// }
	// return false;
	// }
	//
	// public void startAPP(String appPackageName) {
	// try {
	// Intent intent = this.getPackageManager().getLaunchIntentForPackage(
	// appPackageName);
	// startActivity(intent);
	// } catch (Exception e) {
	// Toast.makeText(this, "没有安装", Toast.LENGTH_LONG).show();
	// }
	// }
}
